package com.backend.demo1.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.backend.demo1.config.ApiResponse;
import com.backend.demo1.models.NonMember;
import com.backend.demo1.services.AuthService;
import com.backend.demo1.services.NonMemberService;
import com.backend.demo1.utils.JwtUtil;

@RestController
@RequestMapping("/api/non_members")
public class NonMemberController {

    @Autowired
    private NonMemberService nonMemberService;

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtUtil jwtUtil;



    // 添加非会员
    @PostMapping
    public ResponseEntity<ApiResponse<Void>> addNonMember(
            @RequestHeader("Authorization") String authorizationHeader,
            @RequestBody NonMember nonMember) {
        try {
            String token = authorizationHeader.substring(6); // 去掉 "Token " 前缀
            String username = jwtUtil.extractUsername(token);
            Long userId = authService.findUserIdByUsername(username);

            if (userId != null) {
                // 检查是否已存在该会员（通过 userId）
                boolean exists = nonMemberService.existsByUserId(userId);
                if (exists) {
                    return ResponseEntity.status(HttpStatus.CONFLICT) // 409 Conflict
                            .body(ApiResponse.error(409, "已申请会员"));
                }

                nonMember.setUserId(userId);
                nonMemberService.insert(nonMember);
                return ResponseEntity.status(HttpStatus.CREATED) // 201 Created
                        .body(ApiResponse.success(null));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST) // 400 Bad Request
                        .body(ApiResponse.error(400, "用户不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.error(500, "服务器内部错误: " + e.getMessage()));
        }
    }

    // 根据 ID 查找非会员
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<NonMember>> getNonMember(@PathVariable Long id) {
        try {
            NonMember nonMember = nonMemberService.findById(id);
            if (nonMember != null) {
                return ResponseEntity.ok() // 200 OK
                        .body(ApiResponse.success(nonMember));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND) // 404 Not Found
                        .body(ApiResponse.error(404, "非会员不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.error(500, "服务器内部错误: " + e.getMessage()));
        }
    }

    // 获取所有非会员
    @GetMapping
    public ResponseEntity<ApiResponse<List<NonMember>>> getAllNonMembers() {
        try {
            List<NonMember> nonMembers = nonMemberService.findAll();
            return ResponseEntity.ok() // 200 OK
                    .body(ApiResponse.success(nonMembers));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.error(500, "服务器内部错误: " + e.getMessage()));
        }
    }

    // 更新非会员信息
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> updateNonMember(
            @PathVariable Long id,
            @RequestBody NonMember nonMember) {
        try {
            // 确保更新时 ID 一致
            if (nonMember.getUserId() == null || !nonMember.getUserId().equals(id)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST) // 400 Bad Request
                        .body(ApiResponse.error(400, "ID 不匹配"));
            }
            nonMemberService.update(nonMember);
            return ResponseEntity.ok() // 200 OK
                    .body(ApiResponse.success(null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.error(500, "服务器内部错误: " + e.getMessage()));
        }
    }

    // 删除非会员
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteNonMember(@PathVariable Long id) {
        try {
            nonMemberService.deleteById(id);
            return ResponseEntity.ok() // 200 OK（或 204 No Content，根据业务需求选择）
                    .body(ApiResponse.success(null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.error(500, "服务器内部错误: " + e.getMessage()));
        }
    }
}